package com.bims.jreport.pdf.builder;

import com.bims.jreport.pdf.CustomBody;
import com.bims.jreport.pdf.CustomOption;
import com.bims.jreport.pdf.fields.BasePdfFormField;
import com.bims.jreport.utils.DocumentUtil;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.*;

import java.io.OutputStream;
import java.util.*;

import static com.bims.jreport.constant.ReportConstants.DEFAULT_PDF_PAGE_INDEX;

/**
 * 多个PDF构建
 * 目前只生成PDF/A模式
 *
 * @author wangrenjie
 */

public class MultiPdfBuilder extends BaseBuilder {


    private List<CustomBody> bodys;


    //页面页边距
    private float[] margins;


    public MultiPdfBuilder(PageSize pageSize, CustomOption customOption, BuilderContext context, List<CustomBody> bodys) {
        super(pageSize, customOption, context);
        this.bodys = bodys;
    }


    /**
     * 创建单页PDF
     *
     * @param table
     * @return
     */
    private PdfDocument creat(CustomBody body, int pageIndex) {
        PdfBuilder pdfBuilder = new PdfBuilder(this.getPageSize(), this.getCustomOption(), this.getContext(), pageIndex);
        return pdfBuilder.body(body).form(this.getFormFields(pageIndex)).margin(this.margins).footer().header().watermark().build();
    }

    /**
     * 页面边距设置
     * margins： [0]upper margin [1]right margin [2]the left margin [3]the lower margin
     *
     * @param margins
     * @return this
     */
    @Override
    MultiPdfBuilder margin(float[] margins) {
        this.margins = margins;
        return this;
    }

    /**
     * 获得当前页自定义表单域
     */
    private Set<BasePdfFormField> getFormFields(int pageIndex) {
        BuilderContext context = this.getContext();
        return context.getFormFields(pageIndex);
    }

    /**
     * 写入页眉
     *
     * @return this
     */
    @Override
    MultiPdfBuilder header() {
        return this;
    }

    /**
     * 写入页脚
     *
     * @return this
     */
    @Override
    MultiPdfBuilder footer() {
        return this;
    }

    /**
     * 写入水印
     *
     * @return this
     */
    @Override
    MultiPdfBuilder watermark() {
        return this;
    }

    /**
     * 合并 输出文档对象
     *
     * @return 文档对象
     */
    @Override
    public PdfDocument build() {
        List<PdfDocument> documents = new ArrayList<>();
        int pageIndex = DEFAULT_PDF_PAGE_INDEX;
        for (CustomBody body : this.bodys) {
            documents.add(this.creat(body, pageIndex));
            pageIndex++;
        }
        return DocumentUtil.merge(documents);
    }


    /**
     * 输出文件流对象
     *
     * @return 文件输出流
     */
    @Override
    public OutputStream buildStream() {
        return this.build().getWriter().getOutputStream();
    }
}
